// custom-tab-bar/index.js

// 本地工具函数：Promise 化的 wx.request
function wxRequest(options) {
  return new Promise((resolve, reject) => {
    const app = getApp()
    const defaultOptions = {
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    }

    // 合并配置
    const requestOptions = {
      ...defaultOptions,
      ...options,
      header: {
        ...defaultOptions.header,
        ...options.header
      }
    }

    // 自动添加 baseUrl
    if (requestOptions.url && !requestOptions.url.startsWith('http')) {
      requestOptions.url = app.globalData.baseUrl + requestOptions.url
    }

    // 自动添加 token
    const token = wx.getStorageSync('token')
    if (token && !requestOptions.header.Authorization) {
      requestOptions.header.Authorization = token
    }

    wx.request({
      ...requestOptions,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// API 简化方法
const api = {
  get(url, data = {}) {
    return wxRequest({ url, method: 'GET', data })
  }
}

Component({
  data: {
    selected: 0,
    color: "#a0aec0",
    selectedColor: "#667eea",
    backgroundColor: "#ffffff",
    list: [
      {
        pagePath: "/pages/index/index",
        text: "首页",
        iconType: "home"
      },
      {
        pagePath: "/pages/labor/list/list", 
        text: "劳务",
        iconType: "labor"
      },
      {
        pagePath: "/pages/publish/publish",
        text: "发布", 
        iconType: "publish"
      },
      {
        pagePath: "/pages/secondhand/list/list",
        text: "二手",
        iconType: "secondhand"
      },
      {
        pagePath: "/pages/profile/profile",
        text: "我的",
        iconType: "profile"
      }
    ]
  },

  attached() {
    // 组件初始化
  },

  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({ url })
      this.setData({
        selected: data.index
      })
    },

  }
})
